package com.frx.leetcode.packageone;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * @author ：frx
 * @date ：Created in 2019/3/5 21:47
 * @description：  LeedCode 349 题，求两个数组的交集
 *               Input : nums1 = [1,2,2,1], nums2 = [2,2]
 * @modified By：Output : [2]
 * @version: ToDO
 */
public class Intersection {


    public int[] intersection(int[] nums1,int[] nums2){

        TreeSet<Integer> treeSet = new TreeSet<>();

        for (int num : nums1){
            treeSet.add(num);
        }
        ArrayList<Integer > list = new ArrayList<>();
        for (int num : nums2){
            if (treeSet.contains(num)){
                list.add(num);
                treeSet.remove(num);
            }
        }

        int[] nums = new int[list.size()];

        for (int i = 0; i < list.size(); i ++){
            nums[i] = list.get(i);
        }

        return nums;
    }

    /**  NO.350 求两个数的交集 II
     *  Input: nums1[1,2,2,1] nums2[2,2]
     *  Output: [2,2]
     * */
    public static int[] solution(int[] nums1,int[] nums2){

        TreeMap<Integer,Integer> treeMap = new TreeMap<>();

        for (int num : nums1){
            if (treeMap.containsKey(num)){
                treeMap.put(num,treeMap.get(num)+1);
            } else {
                treeMap.put(num,1);
            }
        }
        ArrayList<Integer> list = new ArrayList<>();
        for (int num : nums2){
            if (treeMap.containsKey(num) && treeMap.get(num)!=0){
                list.add(num);
                treeMap.put(num,treeMap.get(num)-1);
            }
        }
        int[] nums = new int[list.size()];

        for (int i = 0; i < list.size(); i++){
            nums[i] = list.get(i);
        }

        return nums;
    }

    public static void main(String[] args){
        int[] nums1 = {1,2,2,1};
        int[] nums2 = {2,2};

        System.out.println(Arrays.toString(solution(nums2,nums1)));
    }
}
